import sys
sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
from tensorflow.keras.models import load_model
import matplotlib.pylab as plt
import numpy as np
import cv2
import tensorflow as tf
from array import array
# from mnist import plot_value_array
# from mnist import plot_image

img = cv2.imread("./eight.png")
# 给img打标签
img_label=np.array([8])
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 联通黑色区域或去除白色噪点（黑笔白底）
dilate_img = cv2.erode(img, None, iterations=8)


# 重设图片大小
new_image = cv2.resize(dilate_img,(28,28),cv2.INTER_CUBIC)
print(new_image.shape)
 # 二值化
ret, thresh_img = cv2.threshold(new_image, 127, 255, cv2.THRESH_BINARY) 
# 图像取反
image_inverse = ~thresh_img
# 增加维度下下面一句也可以调尺寸，但是输出结果是5，很奇怪
reshape_img = (np.expand_dims(image_inverse,0))
# reshape_img = thresh_img.reshape(1,28,28)
print(reshape_img.shape)
# cv2.imshow("img",img )
# cv2.imshow("reshape_img",reshape_img )
# cv2.imshow("thresh_img",thresh_img )
model = load_model('./mnistnum.h5')


# 获取正确率和时间
test_loss, test_acc = model.evaluate(reshape_img,  img_label, verbose=2)
# 输出时间和正确率
print('\nTest time:', test_loss)
print('\nTest accuracy:', test_acc)

result = model.predict(reshape_img)
print(result)
# 输出预测数字
print(np.argmax(result[0]))

# cv2.waitKey(0)

# i=0
# plt.figure(figsize=(6,3))
# plt.subplot(1,2,1)
# plt.imshow(result, cmap=plt.cm.binary)
# mnist.plot_value_array()